package org.hako.recite.word.parser.factory;

import java.util.HashMap;
import java.util.Map;

import org.hako.recite.word.parser.WordListParser;
import org.hako.recite.word.parser.impl.DataFileWordListParser;
import org.hako.recite.word.parser.impl.ExcelWordListParser;
import org.hako.recite.word.parser.impl.OpenOfficeSpreadSheetWordListParser;
import org.hako.recite.word.parser.impl.TextFileWordListParser;
import org.hako.recite.word.parser.impl.UnsupportedFileExtensionException;

/**
 * Factory of {@link WordListParser}. This class will return different implement
 * of {@link WordListParser} by file extension.
 * <table border="1">
 * <tr>
 * <td>File Extension</td>
 * <td>Implement</td>
 * </tr>
 * <tr>
 * <td>txt</td>
 * <td>{@link TextFileWordListParser}</td>
 * </tr>
 * <tr>
 * <td>xls</td>
 * <td>{@link ExcelWordListParser}</td>
 * </tr>
 * <tr>
 * <td>ods</td>
 * <td>{@link OpenOfficeSpreadSheetWordListParser}</td>
 * </tr>
 * <tr>
 * <td>dat</td>
 * <td>{@link DataFileWordListParser}</td>
 * </tr>
 * </table>
 * 
 * @since 0.4.0
 * @author <a href="mailto:xnnyygn@gmail.com">xnnyygn</a>
 */
public class WordListParserFactory {

	private Map<String, WordListParser> parserMap;
	private WordListParser defaultParser;

	/**
	 * Create
	 */
	public WordListParserFactory() {
		super();
		parserMap = new HashMap<String, WordListParser>();
		parserMap.put("txt", new TextFileWordListParser());
		parserMap.put("xls", new ExcelWordListParser());
		parserMap.put("ods", new OpenOfficeSpreadSheetWordListParser());
		parserMap.put("dat", new DataFileWordListParser());
		defaultParser = parserMap.get("txt");
	}

	/**
	 * Get default {@link WordListParser}.
	 * 
	 * @return
	 */
	public WordListParser getParser() {
		return defaultParser;
	}

	/**
	 * Get parser for given file.
	 * 
	 * @param filePath
	 * @return parser
	 * @throws UnsupportedFileExtensionException
	 *             if no appropriate parser for file by extension
	 */
	public WordListParser getParser(String filePath)
			throws UnsupportedFileExtensionException {
		String fileExtension = getExtension(filePath).toLowerCase();
		WordListParser parser = parserMap.get(fileExtension);
		if (parser == null) {
			throw new UnsupportedFileExtensionException(fileExtension);
		}
		return parser;
	}

	/**
	 * Get extension of file path.
	 * 
	 * @param filePath
	 * @return
	 */
	String getExtension(String filePath) {
		int index = filePath.lastIndexOf('.');
		if (index < 0) {

			// no extension
			return "";
		}
		return filePath.substring(index + 1);
	}
}
